//
//  CommentViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/27.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentKey.h"
#import "CommentTableViewCell.h"
#import "MLArticleComment.h"

@interface CommentViewController ()<UITableViewDelegate,UITableViewDataSource,CommentKeyDelegate>

//视图列表
@property (nonatomic, strong)UITableView *tableView;

// 评论内容列表
@property (nonatomic, strong) NSMutableArray *comments;

// 评论用户
@property (nonatomic, strong) MLUser *currentUser;
@property (nonatomic, strong) MLUser *replyUser;
@property (nonatomic)BOOL isReply;
@property (nonatomic, strong)CommentKey *commentkey;

@end

@implementation CommentViewController
{
    UILabel *placeHold;

}

#pragma mark - lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isReply = NO;
    // Do any additional setup after loading the view.
    self.commentkey = [[CommentKey alloc] init];
    
    self.title = @"评论";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    self.currentUser = [MLUser currentUser];
     self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight)style:UITableViewStylePlain];
   
    self.tableView.backgroundColor = RGBA(244, 244, 244, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(205, 205, 205, 1);//分隔条颜色
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);//偏移量
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 50, 0);//滚动条偏移量
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 55, 0, 0)];
    [self.view addSubview:self.tableView];
    // 键盘的代理
    [self.commentkey textViewShowView:self customKeyboardDelegate:self];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    // 加载文章评论
    [self loadComments];
}
- (NSMutableArray *)comments
{
    if (!_comments) {
        _comments = [NSMutableArray array];
    }
    return _comments;
}
#pragma mark - init
// 加载评论
- (void)loadComments {
    AVQuery *commentQuery = [MLArticleComment query];
    [commentQuery whereKey:@"article" equalTo:self.article];
    [commentQuery includeKey:@"user"];
    [commentQuery includeKey:@"reply_user"];
    [commentQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (MLArticleComment *article in objects) {
                if (article.content&&article.content.length) {
                    [self.comments addObject:article];
                }else{
                    [article deleteInBackground];
                }
            }
            [self.tableView reloadData];
        }
    }];
    
}



#pragma mark - textView delegage

// 保存评论内容
-(void)talkBtnClick:(UITextView *)textViewGet
{
    
    // TODO 去除前面的回复
    MLArticleComment *comment = [MLArticleComment object];
    comment.article = self.article;
    
    comment.content = textViewGet.text;
    comment.user = self.currentUser;
    if (self.isReply) {
        comment.reply_user = self.replyUser;
        comment.type = MLArticleCommentType_REPLY;
        self.isReply = NO;
    }else{
        self.isReply = NO;
        comment.type = MLArticleCommentType_NORMAL;
    }
//    comment.reply_user = self.currentUser;
    comment.status = 0;
    [comment saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            // 清除输入框
            self.commentkey.mTextView.text = nil;
            self.commentkey.placeholder.alpha = 1;
            // 添加到评论列表并刷新
            [self.comments addObject:comment];
            [self.tableView reloadData];
            //增加文章的评论计数
           // self.article.commentCount ++;
            [self.article incrementKey:@"commentCount" byAmount:[NSNumber numberWithInteger:+1]];
            [self.article saveInBackground];
        }
    }];
}


#pragma mark - tableView delegage

- (CommentTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"CommentCell" ;
    //自定义cell类
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[CommentTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        
    }
    // 如果评论列表为空则返回空cell
    if (!self.comments) {
        return cell;
    }
    
    MLArticleComment *comment = self.comments[indexPath.row];
    
    MLUser *commentUser = (MLUser *)comment.user;
    
    cell.userNameLabel.text = commentUser.nickname;
   // [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:commentUser.avatar.url]];
    if (!commentUser.subAvatar || [commentUser.subAvatar isEqualToString:@""]) {
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:commentUser.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        
    }else{
        [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:commentUser.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
    }
    cell.userCityLabel.text = commentUser.location_city;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd HH:mm"];
    cell.userTimeLabel.text = [formatter stringFromDate:comment.createdAt];
    cell.gender = commentUser.gender;
    NSString *str = comment.content;
    if (comment.reply_user&&((MLUser *)comment.reply_user).nickname&&comment.type == MLArticleCommentType_REPLY) {
        NSString *nStr = [NSString stringWithFormat:@"回复 %@:",((MLUser *)comment.reply_user).nickname];
        if([comment.content hasPrefix:nStr]){
             str = [NSString stringWithFormat:@"%@",comment.content];
        }else{
            str = [NSString stringWithFormat:@"回复 %@:%@",((MLUser *)comment.reply_user).nickname,comment.content];
        }
        
       
    }
    NSAttributedString *attributedString = [NSAttributedString emotionAttributedStringFrom:str attributes:@{NSFontAttributeName: [UIFont fontWithName:FontName size:13]}];
    CGRect attributeRect = [attributedString boundsWithSize:CGSizeMake(DeviceWidth - 65,CGFLOAT_MAX)];
    cell.CommentCLabel.frame=CGRectMake(55, 55, DeviceWidth - 65, attributeRect.size.height);
    cell.CommentCLabel.text = str;
    
    cell.backgroundColor = [UIColor clearColor];
    
    return  cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CommentTableViewCell *cell = (CommentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    MLArticleComment *comment = self.comments[indexPath.row];
    MLUser *commentUser = (MLUser *)comment.user;
    self.replyUser = commentUser;
      self.isReply = YES;
    NSString *CommentText = self.commentkey.mTextView.text;
   

    if (![CommentText isEqualToString:[NSString stringWithFormat:@"回复 %@:",cell.userNameLabel.text]]) {
        if (![CommentText isEqualToString:@"点击评论..."] || [CommentText isEqualToString:cell.userNameLabel.text]) {
            HJActionSheet *sheet = [[HJActionSheet alloc]initWithTitle:nil Delegate:self destructiveButtonTitle:@"取消" OtherButtonTitles:@[[NSString stringWithFormat:@"回复 %@:",cell.userNameLabel.text]]];
            [sheet show];
            return;
        }
    }
    
    self.commentkey.mTextView.text =[NSString stringWithFormat:@"回复 %@:",cell.userNameLabel.text];
    [self.commentkey textRecover];
    [self.commentkey.mTextView becomeFirstResponder];

  
    
}
-(void)hjActionSheet:(UIButton *)sender clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        self.isReply = YES;
       self.commentkey.mTextView.text = @"";//sender.titleLabel.text;
        [self.commentkey textRecover];
        [self.commentkey.mTextView becomeFirstResponder];
    }else{
        self.isReply = NO;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.comments.count;//Cell个数
    
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentTableViewCell *cell = (CommentTableViewCell *)[self tableView:_tableView cellForRowAtIndexPath:indexPath];
    
    return cell.CommentCLabel.bounds.size.height + 65;
}

//当键盘退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, self.commentkey.keyhHigh, 0);//偏移量
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, self.commentkey.keyhHigh, 0);//滚动条偏移量
}

-(void)dealloc //移除通知
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}


@end
